package com.qf.servlet;

import com.qf.entity.Product;
import com.qf.service.impl.ProductServiceImpl;
import com.qf.service.ProductService;
import com.qf.utils.JsonUtils;
import com.qf.utils.PageUtils;
import com.qf.utils.ResultVo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @title:ProducteServlet
 * @Descripe:
 * @author:Wjl
 * @date:2023/4/20 14:19
 */
@WebServlet(name = "productServlet",urlPatterns = "/productServlet")
public class ProductServlet extends BaseServlet {

    private ProductService productService = new ProductServiceImpl();
    /**
     * 查询product的全部数据
     * @param request
     * @param response
     */
    public void selectAllProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String ps_id =request.getParameter("ps_id");        //商品状态
        String pt_id =request.getParameter("pt_id");        //商品类型
        String pro_name =request.getParameter("pro_name");  //商品名称
        String currentPageNoStr =request.getParameter("currentPageNo");     //当前第几页
        String pageSizeStr =request.getParameter("pageSize");   //当前页的数据条数

        PageUtils<Product> productPageUtils = productService.selectAllProduct(ps_id, pt_id, pro_name, currentPageNoStr, pageSizeStr);

        ResultVo<PageUtils<Product>> resultVo = new ResultVo<>();
        if (productPageUtils==null){
            resultVo.setCode(500);
            resultVo.setData(null);
            resultVo.setMessage("没有数据");
        }else {
            resultVo.setCode(200);
            resultVo.setData(productPageUtils);
            resultVo.setMessage("查询成功");
        }
        PrintWriter pw = response.getWriter();
        JsonUtils.showJson(pw,resultVo);
    }

    /**
     * 添加商品
     * @param request
     * @param response
     */
    public void addProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //创建服务器文件夹来保存文件
        String realPath = request.getServletContext().getRealPath("WEB-INF/upload");
        //构建File对象
        File file = new File(realPath);
        //判断是否含有该文件，没有则创建
        if (!file.exists()){
            file.mkdirs();
            System.out.println("服务器创建了文件夹");
        }
        String pro_name =null;
        String pro_photo =null;
        String ps_idStr=null;
        String pro_purchasing_priceStr=null;
        String pro_sale_priceStr=null;
        String pro_numberStr=null;
        String pt_idStr=null;

        //判断图片是否上传成功
        boolean photo = false;
        //提交给前端
        ResultVo<Boolean> resultVo = new ResultVo<>();
        PrintWriter pw = response.getWriter();
        //判断前端请求方式是否为文件
        boolean flag = ServletFileUpload.isMultipartContent(request);
            if (flag){
                //获取工厂对象
                DiskFileItemFactory dff = new DiskFileItemFactory();
                //获取文件核心对象
                ServletFileUpload sfu = new ServletFileUpload(dff);

                //获取<from><from>里提交过来所有标签条目
                List<FileItem> fileItemlist =null;
                try {
                    fileItemlist = sfu.parseRequest(request);
                } catch (FileUploadException e) {
                    e.printStackTrace();
                }

                //遍历全部标签条目
                for (FileItem fileItem:fileItemlist) {
                    if (fileItem.isFormField()){    //判断是否是普通文本
                        //获取该类型的name属性的值
                        String name=fileItem.getFieldName();
                        System.out.println(name);   //测试输出的是写入的value值
                        if ("pro_name".equals(name)){
                            pro_name=fileItem.getString("UTF-8");
                        }
                        if ("ps_id".equals(name)){
                            ps_idStr=fileItem.getString("UTF-8");
                        }
                        if ("pro_purchasing_price".equals(name)){
                            pro_purchasing_priceStr=fileItem.getString("UTF-8");
                        }
                        if ("pro_sale_price".equals(name)){
                            pro_sale_priceStr=fileItem.getString("UTF-8");
                        }
                        if ("pro_number".equals(name)){
                            pro_numberStr=fileItem.getString("UTF-8");
                        }
                        if ("pt_id".equals(name)){
                            pt_idStr=fileItem.getString("UTF-8");
                        }
                    }else{
                        //获取文件名
                        String oldName =fileItem.getName();
                        System.out.println(oldName);
                        //判断文件名格式
                        if (oldName.endsWith(".jpg")||oldName.endsWith(".jpeg")||oldName.endsWith(".png")){
                            //新文件名(以原文件的格式结尾)
                            String fieldName = System.currentTimeMillis()+oldName;
                            //存储位置+文件名
                            File f = new File(file,fieldName);
                            pro_photo=fieldName;
                            try {
                                //向服务器写入图片(在out文件夹里)
                                fileItem.write(f);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            photo=true;
                        }else{
                            JsonUtils.showJson(pw,resultVo);
                            resultVo.setCode(500);
                            resultVo.setData(false);
                            resultVo.setMessage("图片上传失败");
                        }
                    }
                }
            }else {
                System.out.println("非文件提交形式");
            }
        if (photo==true){
//            System.out.println(pro_name);
//            System.out.println(pro_photo);
//            System.out.println(ps_idStr);
//            System.out.println(pro_purchasing_priceStr);
//            System.out.println(pro_sale_priceStr);
//            System.out.println(pro_numberStr);
//            System.out.println(pt_idStr);
            int i=productService.addProduct(pro_name,pro_photo,ps_idStr,pro_purchasing_priceStr,pro_sale_priceStr,pro_numberStr,pt_idStr,new Date());
            System.out.println(i);
            if (i>0) {
                resultVo.setCode(500);
                resultVo.setData(true);
                resultVo.setMessage("添加成功");
                JsonUtils.showJson(pw,resultVo);

            }else {
                resultVo.setCode(200);
                resultVo.setData(false);
                resultVo.setMessage("添加失败");
                JsonUtils.showJson(pw,resultVo);
            }
        }
    }

    /**
     * 通过id删除商品
     * @param request
     * @param response
     * @throws IOException
     */
    public void delProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String pro_id = request.getParameter("pro_id");
        int i = productService.delProduct(pro_id);

        ResultVo<Boolean> resultVo = new ResultVo<>();
        PrintWriter pw = response.getWriter();
        if (i>0) {
            resultVo.setCode(500);
            resultVo.setData(true);
            resultVo.setMessage("删除成功");
            JsonUtils.showJson(pw,resultVo);

        }else {
            resultVo.setCode(200);
            resultVo.setData(false);
            resultVo.setMessage("删除失败");
            JsonUtils.showJson(pw,resultVo);
        }
    }

    /**
     * 跳转到修改页面
     * @param request
     * @param response
     */
    public void GoUpdateProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String pro_id = request.getParameter("pro_id");
        Product product = productService.selectById_Or_Name(pro_id, null);
        ResultVo<Product> resultVo = new ResultVo<>();
        PrintWriter pw = response.getWriter();
        if (product!=null) {
            resultVo.setCode(500);
            resultVo.setData(product);
            resultVo.setMessage("查询成功");
            JsonUtils.showJson(pw,resultVo);

        }else {
            resultVo.setCode(200);
            resultVo.setData(null);
            resultVo.setMessage("查询失败");
            JsonUtils.showJson(pw,resultVo);
        }
    }
    /**
     * 通过id修改商品
     * @param request
     * @param response
     */
    public void updateProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //创建服务器文件夹来保存文件
        String realPath = request.getServletContext().getRealPath("WEB-INF/upload");
        //构建File对象
        File file = new File(realPath);
        //判断是否含有该文件，没有则创建
        if (!file.exists()){
            file.mkdirs();
            System.out.println("服务器创建了文件夹");
        }

        String pro_idStr =null;
        String pro_name =null;
        String pro_photo =null;
        String ps_idStr=null;
        String pro_purchasing_priceStr=null;
        String pro_sale_priceStr=null;
        String pro_numberStr=null;
        String pt_idStr=null;

        Map<String,String> proMap =new HashMap<>();
        proMap.put("pro_id",pro_idStr);
        proMap.put("pro_name",pro_name);
        proMap.put("pro_photo",pro_photo);
        proMap.put("ps_id",ps_idStr);
        proMap.put("pro_purchasing_price",pro_purchasing_priceStr);
        proMap.put("pro_sale_price",pro_sale_priceStr);
        proMap.put("pro_number",pro_numberStr);
        proMap.put("pt_id",pt_idStr);

        //判断图片是否上传成功
        boolean photo = false;
        //提交给前端
        ResultVo<Boolean> resultVo = new ResultVo<>();
        PrintWriter pw = response.getWriter();
        //判断前端请求方式是否为文件
        boolean flag = ServletFileUpload.isMultipartContent(request);
        if (flag){

            DiskFileItemFactory dff = new DiskFileItemFactory();
            //获取文件核心对象
            ServletFileUpload sfu = new ServletFileUpload(dff);

            //获取<from><from>里提交过来所有标签条目
            List<FileItem> fileItemlist =null;
            try {
                fileItemlist = sfu.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }

            //遍历全部标签条目
            for (FileItem fileItem:fileItemlist) {
                if (fileItem.isFormField()){    //判断是否是普通文本
                    //获取该类型的name属性的值
                    String name=fileItem.getFieldName();
                    System.out.println(name);   //测试输出的是写入的value值
                    if ("pro_id".equals(name)){
                        pro_idStr=fileItem.getString("UTF-8");
                    }
                    if ("pro_name".equals(name)){
                        pro_name=fileItem.getString("UTF-8");
                    }
                    if ("ps_id".equals(name)){
                        ps_idStr=fileItem.getString("UTF-8");
                    }
                    if ("pro_purchasing_price".equals(name)){
                        pro_purchasing_priceStr=fileItem.getString("UTF-8");
                    }
                    if ("pro_sale_price".equals(name)){
                        pro_sale_priceStr=fileItem.getString("UTF-8");
                    }
                    if ("pro_number".equals(name)){
                        pro_numberStr=fileItem.getString("UTF-8");
                    }
                    if ("pt_id".equals(name)){
                        pt_idStr=fileItem.getString("UTF-8");
                    }
                }else{
                    //获取文件名
                    String oldName =fileItem.getName();
                    System.out.println(oldName);
                    //判断文件名格式
                    if (oldName.endsWith(".jpg")||oldName.endsWith(".jpeg")||oldName.endsWith(".png")){
                        //新文件名(以原文件的格式结尾)
                        String fieldName = System.currentTimeMillis()+oldName;
                        //存储位置+文件名
                        File f = new File(file,fieldName);
                        pro_photo=fieldName;
                        try {
                            //向服务器写入图片(在out文件夹里)
                            fileItem.write(f);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        photo=true;
                    }else{
                        JsonUtils.showJson(pw,resultVo);
                        resultVo.setCode(500);
                        resultVo.setData(false);
                        resultVo.setMessage("图片上传失败");
                    }
                }
            }
        }else {
            System.out.println("非文件提交形式");
        }
        if (photo==true){
//            System.out.println(pro_name);
//            System.out.println(pro_photo);
//            System.out.println(ps_idStr);
//            System.out.println(pro_purchasing_priceStr);
//            System.out.println(pro_sale_priceStr);
//            System.out.println(pro_numberStr);
//            System.out.println(pt_idStr);
            int i=productService.updateProduct(proMap);
            System.out.println(i);
            if (i>0) {
                resultVo.setCode(500);
                resultVo.setData(true);
                resultVo.setMessage("修改成功");
                JsonUtils.showJson(pw,resultVo);

            }else {
                resultVo.setCode(200);
                resultVo.setData(false);
                resultVo.setMessage("修改失败");
                JsonUtils.showJson(pw,resultVo);
            }
        }

    }
}
